﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MDX_Studio_v2
{
	public partial class ConnectionWindow : Form
	{
		internal Context _Context = new Context();
		internal Context Context
		{
			get { return _Context; }
			set { _Context = value; }
		}

		// Context Delegates
		public delegate void ContextUpdatedHandler(object sender, Context e);
		public event ContextUpdatedHandler ContextUpdated;

		// Background workers
		private BackgroundWorker bg_Connecter = new BackgroundWorker();


		/// <summary>
		/// Form Constructor
		/// </summary>
		public ConnectionWindow()
		{
			InitializeComponent();

			bg_Connecter.DoWork += bg_Connecter_DoWork;
			bg_Connecter.RunWorkerCompleted += bg_Connecter_RunWorkerCompleted;
		}

		void bg_Connecter_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			Cursor.Current = Cursors.Default;

			Microsoft.AnalysisServices.DatabaseCollection catalogs = _Context.Connection.ListCatalogs();

			if (catalogs != null)
			{
				foreach (Microsoft.AnalysisServices.Database catalog in catalogs)
				{
					drop_InitialCatalog.Items.Add(catalog.Name);
				}
			}
		}

		void bg_Connecter_DoWork(object sender, DoWorkEventArgs e)
		{
			Cursor.Current = Cursors.WaitCursor;
			try
			{
				if (!_Context.Connection.ConnectToServer())
				{
					_Context.MainForm.AddResultMessage("Unable to connect to server '" + _Context.Connection.ServerName + "'", false);
					return;
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine("ConnectionWindow.cs\\box_ServerName_Leave: {0}", ex.Message);
			}
		}

		/// <summary>
		/// Event fired on load of the form
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void ConnectionWindow_Load(object sender, EventArgs e)
		{
			if( _Context.Connection != null ) box_ServerName.Text = _Context.Connection.ServerName;
		}

		/// <summary>
		/// Event fired once the Server Name box has been exited
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void box_ServerName_Leave(object sender, EventArgs e)
		{
			drop_InitialCatalog.Items.Clear();	// Clear Catalogs list

			if (box_ServerName.Text.Trim().Length < 1) return;

			_Context.Connection.ServerName = box_ServerName.Text.Trim();

			bg_Connecter.RunWorkerAsync();
		}

		/// <summary>
		/// Event fired once the Catalog dropdown has been left
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void drop_InitialCatalog_Leave(object sender, EventArgs e)
		{
			drop_InitialCube.Items.Clear();		//Clear Cubes list
			try
			{
				if (drop_InitialCatalog.SelectedItem.ToString().Length > 0)
				{
					drop_InitialCube.Enabled = true;

					Microsoft.AnalysisServices.CubeCollection cubes = _Context.Connection.ListCubes(drop_InitialCatalog.SelectedItem.ToString());

					if (cubes != null)
					{
						foreach (Microsoft.AnalysisServices.Cube cube in cubes)
						{
							drop_InitialCube.Items.Add(cube.Name);
						}
					}
				}
			}
			catch (Exception ex) { Console.WriteLine("ConnectionWindow.cs\\drop_InitialCatalog_Leave: {0}", ex.Message); }
		}

		/// <summary>
		/// Event fired when the TestConnection button is pressed
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void button_TestConnection_Click(object sender, EventArgs e)
		{
			string server = box_ServerName.Text, cat = null, cube = null;
			try { cat = drop_InitialCatalog.SelectedItem.ToString(); } catch (Exception ex) { Console.WriteLine("ConnectionWindow.cs\\button_TestConnection_Click1: {0}", ex.Message); }
			try { cube = drop_InitialCube.SelectedItem.ToString(); } catch (Exception ex) { Console.WriteLine("ConnectionWindow.cs\\button_TestConnection_Click2: {0}", ex.Message); }

			// TryConnect
			string result = _Context.Connection.TryConnect(server, cat, cube);

			if (result == null) MessageBox.Show("Unspecified error. Unable to connect. Please ensure all entered settings are correct.", "Error");
			else MessageBox.Show(result);
		}

		/// <summary>
		/// Event fired when the Connect button is pressed
		/// Instance settings are saved and transferred to the Main Form
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void button_Connect_Click(object sender, EventArgs e)
		{
			// Get current settings
			string server = box_ServerName.Text, cat = null, cube = null;
			try { cat = drop_InitialCatalog.SelectedItem.ToString(); } catch (Exception ex) { Console.WriteLine("ConnectionWindow.cs\\button_Connect_Click1: {0}", ex.Message); }
			try { cube = drop_InitialCube.SelectedItem.ToString(); } catch (Exception ex) { Console.WriteLine("ConnectionWindow.cs\\button_Connect_Click2: {0}", ex.Message); }

			// Store lcoally
			_Context.Connection.ServerName = server;
			_Context.Connection.Catalog = cat;
			_Context.Connection.Cube = cube;

			// Push context
			ContextUpdated(this, _Context);


			if (_Context.DebugMode) Console.WriteLine(_Context.Connection.ToString());	// Debug

			this.Dispose();
		}

		private void button_Cancel_Click(object sender, EventArgs e)
		{
			this.Dispose();		// Close with no event
		}

		private void button_Save_Click(object sender, EventArgs e)
		{
			// TODO: save defaults
		}
	}
}
